#pragma once

#include <iostream>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "log.hpp"

class Util
{
public:
    //读取文件内容 输出到outStr
    static bool ReadFile(const std::string &path,std::string* outStr)
    {
        if(!outStr) return false;
        struct stat st;
        int n = stat(path.c_str(),&st);
        if(n < 0) return false;

        int filesize = st.st_size;
        outStr->resize(filesize); //提前扩容

        int fd = open(path.c_str(),O_RDONLY);
        if(fd < 0) return false;
        
        n = read(fd,(char*)outStr->c_str(),filesize);
        if(n < 0) return false;

        close(fd);

        logMessage(Info,"Read file %s success!",path.c_str());
        return true;
    }

    //读取报头打一行
    static std::string ReadOneLine(std::string& message,const std::string& sep)
    {
        auto pos = message.find(sep);
        if(pos == std::string::npos) return "";

        std::string ret = message.substr(0,pos); //将\r\n之前的字符串分割
        message.erase(0,pos+sep.size()-1); //清除第一行字符串
        return ret;
    }

    //将第一行分割出三个参数 请求方法 资源路径 HTTP版本
    static bool ParseRequestLine(const std::string &line, std::string *method, std::string *url, std::string *vers)
    {
        std::stringstream ss(line);
        ss >> *method >> *url >> *vers; //格式化输入
        return true;
    }

};